package com.iotproject.studyservice.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.iotproject.servicebase.exceptionhandler.GlobalException;
import com.iotproject.studyservice.entity.StudyListeningType;
import com.iotproject.studyservice.entity.excel.StudyListeningTypeData;
import com.iotproject.studyservice.service.StudyListeningTypeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.StringUtils;

public class StudyListeningTypeExcelListener extends AnalysisEventListener<StudyListeningTypeData> {

    StudyListeningTypeService studyListeningTypeService;

    public StudyListeningTypeExcelListener() {
    }

    public StudyListeningTypeExcelListener(StudyListeningTypeService studyListeningTypeService) {
        this.studyListeningTypeService = studyListeningTypeService;
    }

    @Override
    public void invoke(StudyListeningTypeData studyListeningTypeData, AnalysisContext analysisContext) {
        if (studyListeningTypeData == null) {
            throw new GlobalException(20001, "文件数据为空");
        }
        String name = studyListeningTypeData.getName();
        String cover = studyListeningTypeData.getCover();
        StudyListeningType studyListeningType = existListeningType(studyListeningTypeService, name);
        if (studyListeningType == null) {//不存在
            studyListeningType = new StudyListeningType();
            if (StringUtils.isEmpty(cover)) {
                //默认封面地址
                cover = "https://upload-up.qtfm.cn/user/ffaea5ef6cddcf5844c722a54f6eee28/1597927162_0001-151582953.png";
            }
            studyListeningType.setName(name);
            studyListeningType.setCover(cover);
            studyListeningTypeService.save(studyListeningType);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断类别是否重复
    //可以根据 类别名称name 判断
    public StudyListeningType existListeningType(StudyListeningTypeService studyListeningTypeService, String name) {
        QueryWrapper<StudyListeningType> studyListeningTypeQueryWrapper = new QueryWrapper<>();
        studyListeningTypeQueryWrapper.eq("name", name);
        StudyListeningType studyListeningType = studyListeningTypeService.getOne(studyListeningTypeQueryWrapper);
        return studyListeningType;
    }
}
